import mysql from 'mysql';
import conne from './db.config';

let querys=async npmzat=>{
    const connection =mysql.createConnection(conne)
    connection.connect();
    let results=await new Promise((res,rej)=>{
        connection.query(npmzat,(error,results)=>{
            if(error) rej(error);
            res(results);
        })
    })
    connection.end();
    return results;
}

//方法:
//查看：
let select =tablesName=> querys(`select * from '${tablesName}'`);
//删除;
let dele = (tablesName,condition) =>querys(`delete from '${tablesName}' where '${condition}';`);
//增加;
let insert =(tablesName,obj)=>{
    let keys = Object.keys(obj);
    let values =Object.keys(obj).map(item=>typeof obj[item] === "string"?`'${ obj[item] }'`:obj[item]);
    return querys(`insert into ${tablesName} (${keys.join(',')}) values (${values.join(',')})`);
}
//更新;
let update =async obj=>{
    let keys=Object.keys(obj);
    let values=Object.keys(obj).map(item=>typeof obj[item] === "string"?`'${ obj[item] }'`:obj[item]);
    let results=await querys(`update user set '${values.join(",")}' where id='${values.id}'`);
    console.log(results)
}

export default{
    querys,
    select,
    dele,
    insert,
    update
}